package com.wufun.overseas.main.activity;

import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.papa.controller.core.ControllerManager;
import com.wufun.overseas.R;
import com.wufun.overseas.dialog.HandShankDialog;
import com.wufun.overseas.joystick.map.BlackListManager;
import com.wufun.overseas.main.base.MyApplication;
import com.wufun.overseas.models.bean.CommonRequestBean;
import com.wufun.overseas.models.bean.HandShankAdBean;
import com.wufun.overseas.models.bean.IntentDateBean;
import com.wufun.overseas.models.bean.ResultMainBean;
import com.wufun.overseas.models.db.HandShankTable;
import com.wufun.overseas.models.greendao.gen.HandShankTableDao;
import com.wufun.overseas.rpc.RpcClient;
import com.wufun.overseas.tools.BackgroundExecutor;
import com.wufun.overseas.utils.NetWorkUtils;
import com.wufun.overseas.utils.RequestBeanUtil;
import com.wufun.overseas.view.HandShankAdView;
import com.wufun.overseas.utils.IntentUtil;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by caowd on 2015/6/9.
 * 无手柄页面
 */
public class HandShankNoActivity extends HandShankBaseActivity {

    private HandShankDialog handShankDialog;
    boolean isInputDeviceConnected = false;
    @Bind(R.id.rightButn)
    Button   rightButn;
    @Bind(R.id.papahandList)
    TextView papahandList;
    HandShankTableDao dao;

    @OnClick(R.id.blue_setup_btn)
    public void blue_setup_btn() {
        startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
    }

    @OnClick(R.id.backImage)
    void backImage() {
        finish();
    }

    @OnClick(R.id.papahandList)
    void papahandList() {
        IntentDateBean intentDateBean = new IntentDateBean();
        intentDateBean.setLink_type(4);
        intentDateBean.setLink_type_val("http://h5.papa91.com/wf_shoubing.html");
        IntentUtil.getInstance().goShareWebActivity(this, intentDateBean);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.handshank_layout_no);
        ButterKnife.bind(this);

//        rpcClient = new RpcClient();
        dao = MyApplication.getMyApplication().getSession().getHandShankTableDao();
        AfterViews();
    }

//    @Bind(R.id.mAdView)
//    HandShankAdView mAdView;
//    @RestService
//    RpcClient rpcClient;

    //    @Background
    void getAdData() {
        BackgroundExecutor.execute(new BackgroundExecutor.Task("", 0L, "") {
                                       @Override
                                       public void execute() {
                                           try {
                                               getAdData1();
                                           } catch (final Throwable e) {
                                               Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e);
                                           }
                                       }
                                   }
        );
    }
    void getAdData1() {
//        try {
//            CommonRequestBean               requestBean = DotRequestTable.getInstance(this).getHandShankAdList();
//            ResultMainBean<HandShankAdBean> response    = rpcClient.getHandShankAdList(requestBean);
//            if (response.getCode() == 600) {
//                mAdView.updateViewByData(response.getMessages().getData());
//            } else {
//                mAdView.showDefaultView();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            mAdView.showDefaultView();
//        }
    }

    public void loadAdData() {
        if (NetWorkUtils.isNetworkConnected(this)) {
            getAdData();
        } else {
//            mAdView.showNoNetWork();
        }
    }

    //    @AfterViews
    void AfterViews() {
        loadAdData();
//        //打点
//        StatFactory.getInstance(this).sendDJoystickSetting(AccountUtil_.getInstance_(this).getUid(), AccountUtil_.getInstance_(this).isTourist(), "", "", 0);

        if (rightButn != null)
            rightButn.setVisibility(View.GONE);

    }

    @Override
    protected void onDestroy() {
        if (handShankDialog != null && handShankDialog.isShowing()) {
            handShankDialog.dismiss();
            handShankDialog = null;
        }
        super.onDestroy();
    }

    @Override
    public void onControllerDeviceChanged(int state, List<ControllerManager.ControllerDevice> controllerDevices) {
        checkJoystickJoin(controllerDevices);
    }

    private void checkJoystickJoin(List<ControllerManager.ControllerDevice> devices) {
        if (devices == null || devices.size() == 0) {

            if (handShankDialog != null && handShankDialog.isShowing() && getValidDeviceCount(devices) < 1) {
                handShankDialog.dismiss();
            }
            return;
        }

        String deviceName = "";
        for (ControllerManager.ControllerDevice device : devices) {

            if (!BlackListManager.getInstance().isInBlackList(device.getName())) {

                HandShankTable handShankTable = new HandShankTable();
                handShankTable.setName(device.getName());
                handShankTable.setAddress(device.getAddress());
                handShankTable.setTime(System.currentTimeMillis());
                handShankTable.setIsConnect(true);

                isInputDeviceConnected = true;
                deviceName = device.getName();
                save(handShankTable);

            }
        }
        if (isInputDeviceConnected)
            showTipDialog(deviceName);
    }

    public synchronized void showTipDialog(String name) {
        if (handShankDialog == null || !handShankDialog.isShowing()) {
            handShankDialog = new HandShankDialog(this);
            handShankDialog.setTitle(name);
            handShankDialog.setCancelClick(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    startActivity(new Intent(HandShankNoActivity.this, HandShankYesActivity.class));
                    finish();
                }
            });
            handShankDialog.setCheckClick(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(HandShankNoActivity.this, HandShankCheckKeyActivity.class);
                    intent.putExtra("from", "first");
                    startActivity(intent);
                    finish();
                }
            });
            handShankDialog.show();
        }
    }

    @Override
    protected void onResume() {
        setSpp4CheckInfo(true);
        super.onResume();
    }

    //    @Background
    void save(HandShankTable handShankTable) {
        if (!isExist(handShankTable.getAddress())) {
            createOrUpdate(handShankTable);
            sendJoystickInfo(handShankTable);
        }
    }

    private void sendJoystickInfo(HandShankTable handShankTable) {
//        JoyStickConfig joystickConfig = new JoyStickConfig();
//
//        AccountBean accountBean = AccountUtil_.getInstance_(this).getAccountData();
//        if (accountBean == null)
//            joystickConfig.setUid(0);
//        else
//            joystickConfig.setUid(accountBean.getUid());
//        joystickConfig.setGamepad_name(handShankTable.getName());
//        joystickConfig.setGamepad_mac(handShankTable.getAddress().replace(":", "_"));
//        joystickConfig.setUpdate_time(handShankTable.getTime());

//        StatFactory.getInstance(this).sendJoyStickInfoPost(JsonMapper.nonDefaultMapper().toJson(joystickConfig), AccountUtil_.getInstance_(this).getUid());
    }

    //region DB handle
    public List<HandShankTable> findForTime() {
        List<HandShankTable> list = null;
        try {
            list = null;
            list = dao.queryBuilder().orderDesc(HandShankTableDao.Properties.Time).list();

            for (int i = 0; i < list.size(); i++) {
                HandShankTable handShankTable = list.get(i);
                if (BlackListManager.getInstance().isInBlackList(handShankTable.getName())) {
                    dao.delete(handShankTable);
                    list.remove(i);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public boolean isExist(String address) {
        try {
            List<HandShankTable> list = dao.queryBuilder().orderDesc(HandShankTableDao.Properties.Time).where(HandShankTableDao.Properties.Address.eq(address)).list();
            if (list != null && list.size() > 0)
                return true;
        } catch (Exception e) {
//            e.printStackTrace();
        }
        return false;
    }

    public void createOrUpdate(HandShankTable handShankTable) {
        if (isExist(handShankTable.getAddress())) {
            dao.update(handShankTable);
        } else
            dao.insertOrReplace(handShankTable);
    }
    //endregion
}
